//
//  EWLoginViewController.m
//  eatWhat
//
//  Created by 陈 宁权 on 17/4/1.
//  Copyright © 2017年 陈 宁权. All rights reserved.
//

#import "EWLoginViewController.h"
#import "EWTabBarController.h"
#import "EWBaseNavViewController.h"
#import "EWRegisterViewController.h"
#import "RCDUserInfo.h"
#import "RCDataBaseManager.h"
#import "AppDelegate.h"

@interface EWLoginViewController ()<UITextFieldDelegate,UIWebViewDelegate>

@property (nonatomic,strong) UITextField *userName;
@property (nonatomic,strong) UITextField *password;
@property (nonatomic,strong) UIView *userUnderLine;
@property (nonatomic,strong) UIView *pwdUnderLine;
@property (nonatomic,strong) UIButton *loginBtn;
@property (nonatomic,assign) BOOL userNameIsInput;
@property (nonatomic,assign) BOOL passwordIsInput;
@property (nonatomic,strong) UIView *sheetView;
@property (nonatomic,strong) NSDictionary *salsManagerDic;
@property (nonatomic,assign) BOOL isCorrect;
@property (nonatomic,strong) UIImageView *correctImage;
@property (nonatomic,strong) UIImageView *wrongImage;
@property (nonatomic,strong) UILabel *salesManager;
@property (nonatomic,assign) BOOL isRememberUserAndPwd;
@property (nonatomic,strong) UIImageView *rememberPwdImage;

@end

@implementation EWLoginViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    //添加子视图
    [self addChildView];
}

- (void)addChildView
{
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"背景"]];
    
    _userName = [[UITextField alloc] init];
    _userName.placeholder = @"点击输入用户名";
    UIView *userLeftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    UIImageView *userImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"账户默认"]];
    userImage.center = userLeftView.center;
    [userLeftView addSubview:userImage];
    _userName.backgroundColor = [UIColor whiteColor];
    _userName.leftView = userLeftView;
    _userName.leftViewMode = UITextFieldViewModeAlways;
    _userName.clearButtonMode = UITextFieldViewModeAlways;
    _userName.delegate = self;
    [self.view addSubview:_userName];
    
    _userUnderLine = [[UIView alloc] init];
    _userUnderLine.backgroundColor = [UIColor colorWithRed:0.94 green:0.95 blue:0.95 alpha:1.00];
    [self.view addSubview:_userUnderLine];
    
    _password = [[UITextField alloc] init];
    _password.placeholder = @"点击输入密码";
    _password.secureTextEntry = YES;
    UIView *pwdLeftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    UIImageView *pwdImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"密码默认"]];
    pwdImage.center = userLeftView.center;
    [pwdLeftView addSubview:pwdImage];
    _password.backgroundColor = [UIColor whiteColor];
    _password.leftView = pwdLeftView;
    _password.leftViewMode = UITextFieldViewModeAlways;
    _password.clearButtonMode = UITextFieldViewModeAlways;
    _password.delegate = self;
    [self.view addSubview:_password];
    
    _pwdUnderLine = [[UIView alloc] init];
    _pwdUnderLine.backgroundColor = [UIColor colorWithRed:0.94 green:0.95 blue:0.95 alpha:1.00];
    [self.view addSubview:_pwdUnderLine];
    
    _loginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_loginBtn setTitle:@"登录" forState:UIControlStateNormal];
    [_loginBtn setEnabled:NO];
    [_loginBtn setBackgroundColor:[UIColor colorWithRed:0.81 green:0.82 blue:0.82 alpha:1.00]];
    [_loginBtn addTarget:self action:@selector(login) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_loginBtn];
    
    UIButton *registerBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [registerBtn setTitle:@"新用户注册" forState:UIControlStateNormal];
    [registerBtn setTitleColor:BASE_COLOR forState:UIControlStateNormal];
    registerBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    registerBtn.titleLabel.textAlignment = NSTextAlignmentLeft;
    [registerBtn addTarget:self action:@selector(clickregisterBtn) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:registerBtn];
    
    UIButton *forgetPwdBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [forgetPwdBtn setTitle:@"忘记密码?" forState:UIControlStateNormal];
    [forgetPwdBtn setTitleColor:BASE_COLOR forState:UIControlStateNormal];
    forgetPwdBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    forgetPwdBtn.titleLabel.textAlignment = NSTextAlignmentRight;
    [forgetPwdBtn addTarget:self action:@selector(clickForgetPwdBtn) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:forgetPwdBtn];
    
    UILabel *version = [[UILabel alloc] init];
    version.text = [NSString stringWithFormat:@"当前版本：v%@",[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"]];
    version.textAlignment = NSTextAlignmentCenter;
    version.font = [UIFont systemFontOfSize:15];
    version.textColor = [UIColor grayColor];
    [self.view addSubview:version];
    
    
    [_userName mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(280);
        make.left.equalTo(self.view).offset(42);
        make.right.equalTo(self.view).offset(-42);
        make.height.offset(42);
    }];
    
    [_userUnderLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_userName.mas_bottom).offset(0.1);
        make.left.equalTo(self.view).offset(42);
        make.right.equalTo(self.view).offset(-42);
        make.height.offset(0.5);
    }];
    
    [_password mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_userName.mas_bottom).offset(23);
        make.left.equalTo(self.view).offset(42);
        make.right.equalTo(self.view).offset(-42);
        make.height.offset(42);
    }];
    
    [_pwdUnderLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_password.mas_bottom).offset(0.1);
        make.left.equalTo(self.view).offset(42);
        make.right.equalTo(self.view).offset(-42);
        make.height.offset(0.5);
    }];
    
    [_loginBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_password.mas_bottom).offset(26);
        make.left.equalTo(self.view).offset(42);
        make.right.equalTo(self.view).offset(-42);
        make.height.offset(42);
    }];
    
    [registerBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_loginBtn.mas_bottom).offset(10);
        make.left.equalTo(_loginBtn.mas_left).offset(-10);
        make.width.offset(100);
        make.height.offset(15);
    }];
    
    [forgetPwdBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_loginBtn.mas_bottom).offset(10);
        make.right.equalTo(self.view).offset(-42);
        make.width.offset(70);
        make.height.offset(15);
    }];
    
    [version mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_bottom).offset(-30);
        make.centerX.equalTo(self.view).offset(0);
        make.width.offset(200);
        make.height.offset(15);
    }];

}


- (void)login
{
    [SVProgressHUD showWithStatus:@"正在登录中.."];
    [[BQUserDao shareObject] loginWithUserId:_userName.text andPassword:_password.text andServiceReceiveResponseSuccess:^(id response) {
        
        NSDictionary *areaType = response[@"areaType"];
        [DEFAULTS setObject:areaType[@"userMobile"] forKey:@"userMobile"];
        [DEFAULTS setObject:areaType[@"token"] forKey:@"loginToken"];
        [DEFAULTS setObject:_password.text forKey:@"userPwd"];
        //连接融云服务器
        [[RCIMClient sharedRCIMClient] connectWithToken:areaType[@"token"] success:^(NSString *userId) {
            
            [SVProgressHUD dismiss];
            //回到主线程跳转到首页
            dispatch_async(dispatch_get_main_queue(), ^{
                EWTabBarController *baseTabBarController = [[EWTabBarController alloc] init];
                [self presentViewController:baseTabBarController animated:YES completion:nil];
            });
            
            //设置当前登录用户信息
            RCUserInfo *user = [RCUserInfo new];
            user.userId = _userName.text;
            user.name = areaType[@"userName"];
            user.portraitUri = areaType[@"portraitUri"];
            
            [[RCDataBaseManager shareInstance] insertUserToDB:user complete:^(BOOL result) {
                //设置当前登录用户信息
                [RCIM sharedRCIM].currentUserInfo = user;
                
                [[RCIM sharedRCIM] refreshUserInfoCache:user withUserId:userId];
                
                //从服务器获取数据插入到本地数据库
                
                [self addDataToLocalDataBase];
            }];
            
        } error:^(RCConnectErrorCode status) {
            NSLog(@"错误编码:%ld",(long)status);
            [SVProgressHUD showErrorWithStatus:@"登录失败"];
        } tokenIncorrect:^{
            NSLog(@"token过期或不正确");
            [SVProgressHUD showErrorWithStatus:@"登录失败"];
        }];
        
    } ServiceReceiveResponseFailed:^(id response) {
        [SVProgressHUD showErrorWithStatus:@"登录失败"];
    }];
}

- (void)clickForgetPwdBtn
{
    
}

- (void)addDataToLocalDataBase
{
    [self addFriendInfo];
    //同步群组信息到本地数据库
    [RCDDataSource syncGroups];
}

- (void)addFriendInfo
{
    [[BQUserDao shareObject] queryFriendListWithfId:[RCIM sharedRCIM].currentUserInfo.userId andServiceReceiveResponseSuccess:^(id response) {
        NSMutableArray *Users = response[@"friendList"];
        NSMutableArray *friendList = [NSMutableArray array];
        for (NSDictionary *userinfo in Users) {
            RCDUserInfo *model = [[RCDUserInfo alloc] init];
            model.userId = userinfo[@"userId"];
            model.name = userinfo[@"userName"];
            model.portraitUri = userinfo[@"portraitUri"];
            model.status = userinfo[@"fstatus"];
            model.updatedAt = userinfo[@"createTime"];
            model.displayName = userinfo[@"userName"];
            [friendList addObject:model];
        }
        [[RCDataBaseManager shareInstance] insertFriendListToDB:friendList complete:^(BOOL result) {
            if (!result) {
                [SVProgressHUD showErrorWithStatus:@"获取好友列表失败"];
            }
        }];
    } ServiceReceiveResponseFailed:^(id response) {

    }];
}

- (void)clickregisterBtn
{
    EWRegisterViewController *registerVC = [[EWRegisterViewController alloc] init];
    EWBaseNavViewController *registerNav = [[EWBaseNavViewController alloc] initWithRootViewController:registerVC];
    [self presentViewController:registerNav animated:YES completion:nil];
}

- (BOOL)textFieldShouldClear:(UITextField *)textField
{
    if (_userName == textField)
    {
        _userNameIsInput = NO;
        UIImageView *userImageView = _userName.leftView.subviews[0];
        userImageView.image = [UIImage imageNamed:@"账户默认"];
        _userUnderLine.backgroundColor = [UIColor colorWithRed:0.94 green:0.95 blue:0.95 alpha:1.00];
    }
    
    if (_password == textField)
    {
        _passwordIsInput = NO;
        UIImageView *userImageView = _password.leftView.subviews[0];
        userImageView.image = [UIImage imageNamed:@"密码默认"];
        _pwdUnderLine.backgroundColor = [UIColor colorWithRed:0.94 green:0.95 blue:0.95 alpha:1.00];
    }
    
    if (_userNameIsInput && _passwordIsInput)
    {
        [_loginBtn setEnabled:YES];
        [_loginBtn setBackgroundColor:BASE_COLOR];
    }
    else
    {
        [_loginBtn setEnabled:NO];
        [_loginBtn setBackgroundColor:[UIColor colorWithRed:0.94 green:0.95 blue:0.95 alpha:1.00]];
    }
    return YES;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (_userName == textField)
    {
        if (_userName.text.length > 1 || string.length > 0) {
            _userNameIsInput = YES;
            UIImageView *userImageView = _userName.leftView.subviews[0];
            userImageView.image = [[UIImage imageNamed:@"账户2"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
            userImageView.tintColor = BASE_COLOR;
            _userUnderLine.backgroundColor = BASE_COLOR;
        }
        else
        {
            _userNameIsInput = NO;
            UIImageView *userImageView = _userName.leftView.subviews[0];
            userImageView.image = [UIImage imageNamed:@"账户默认"];
            _userUnderLine.backgroundColor = [UIColor colorWithRed:0.94 green:0.95 blue:0.95 alpha:1.00];
        }
    }
    
    if (_password == textField)
    {
        if (_password.text.length > 1 || string.length > 0) {
            _passwordIsInput = YES;
            UIImageView *userImageView = _password.leftView.subviews[0];
            userImageView.image = [[UIImage imageNamed:@"密码2"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
            userImageView.tintColor = BASE_COLOR;
            _pwdUnderLine.backgroundColor = BASE_COLOR;
        }
        else
        {
            _passwordIsInput = NO;
            UIImageView *userImageView = _password.leftView.subviews[0];
            userImageView.image = [UIImage imageNamed:@"密码默认"];
            _pwdUnderLine.backgroundColor = [UIColor colorWithRed:0.94 green:0.95 blue:0.95 alpha:1.00];
        }
    }
    
    if (_userNameIsInput && _passwordIsInput)
    {
        [_loginBtn setEnabled:YES];
        [_loginBtn setBackgroundColor:BASE_COLOR];
    }
    else
    {
        [_loginBtn setEnabled:NO];
        [_loginBtn setBackgroundColor:[UIColor colorWithRed:0.94 green:0.95 blue:0.95 alpha:1.00]];
    }
    
    
    return YES;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
